package com.matrix.product.listener;

import com.matrix.common.constant.CacheConstants;
import com.matrix.common.constant.RedisConstants;
import com.matrix.common.constant.RocketMQConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 有点甜
 * @since 2025/8/4
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = RocketMQConstants.PRODUCT_CACHE_SYNC_TOPIC,
        consumerGroup = RocketMQConstants.PRODUCT_CACHE_SYNC_CONSUMER_GROUP)
@RequiredArgsConstructor
public class CacheSyncListener implements RocketMQListener<Map<String, String>> {

    private final CacheManager caffeineCacheManager;
    private final CacheManager redisCacheManager;

    @Override
    public void onMessage(Map<String, String> message) {
        try {
            String type = message.get("type");
            String key = message.get("key");

            if (CacheConstants.CACHE_SYNC_TYPE_SHOP_MENU.equals(type) && key != null) {
                String cacheKey = RedisConstants.buildKey(RedisConstants.LOCK_SHOP_MENU_KEY_PREFIX, key);
                log.info("收到缓存同步消息,准备清理店铺菜单缓存, key: {}", cacheKey);

                Cache redisCache = redisCacheManager.getCache(CacheConstants.CACHE_NAME_MENU);
                if (redisCache != null) {
                    redisCache.evict(cacheKey);
                    log.info("Redis 菜单缓存已清理: {}", cacheKey);
                }

                Cache caffeineCache = caffeineCacheManager.getCache("menu");
                if (caffeineCache != null) {
                    caffeineCache.evict(cacheKey);
                    log.info("Caffeine 菜单缓存已清理: {}", cacheKey);
                }
            }
        } catch (Exception e) {
            log.error("处理缓存同步消息失败", e);
        }
    }
}
